import React, { useState, useEffect, memo } from 'react'
import './index.scss'

/*
  点击-倒计时:60
  倒计时未结束前不能点击
*/
let timer = null
function VerifyCode(props) {
  const [time, setTime] = useState(0)

  console.log('倒计时')

  useEffect(() => {
    timer && clearInterval(timer)

    return () => timer && clearInterval(timer)
  }, [])

  useEffect(() => {
    if(time === 0) {
      clearInterval(timer)
    }
  }, [time])

  const handler = () => {
    setTime(props.time || 60) // 修改状态

    timer = setInterval(() => { // 开始倒计时
      setTime(time => time - 1)
    }, 1000);

    props.onClick && props.onClick() // 通知父组件
  }
  return (
    <button className={['verify-code', time ? 'glay' : ''].join(' ')} onClick={handler} type='button' disabled={time !== 0}>
      {time ? `${time}秒后重新获取` : '获取手机验证码'}
    </button>
  )
}

export default memo(VerifyCode)